//
//  MLElementButtonBroadcastView.m
//  CustomerPo
//
//  Created by molon on 8/12/14.
//  Copyright (c) 2014 molon. All rights reserved.
//

#import "MLElementButtonBroadcastView.h"
#import "MLElementButtonBroadcastCell.h"
#import "UIView+MLKit.h"

#define kBroadcastCellPadding 0.0f
@interface MLElementButtonBroadcastView()<MLBroadcastViewDataSource,MLBroadcastViewDelegate>

//轮播总的cell个数
@property (nonatomic, assign) NSInteger broadcastCellCount;
//最大的元素个数在一个cell，当然对应着一个combination
@property (nonatomic, strong) NSMutableArray *maxElementCountsOfCell;

@property (nonatomic, strong) NSMutableArray *combinationCellRanges;

@property (nonatomic, strong) MLBroadcastView *bcView;

@end

@implementation MLElementButtonBroadcastView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.backgroundColor = [UIColor clearColor];
        [self addSubview:self.bcView];
    }
    return self;
}

- (void)dealloc
{
    DLOG(@"MLElementButtonBroadcastView dealloc");
}

#pragma mark - getter
- (MLBroadcastView *)bcView
{
	if (!_bcView) {
		_bcView = [MLBroadcastView new];
		_bcView.delegate = self;
        _bcView.dataSource = self;
        _bcView.padding = kBroadcastCellPadding;
	}
	return _bcView;
}

- (NSMutableArray *)maxElementCountsOfCell
{
	if (!_maxElementCountsOfCell) {
		_maxElementCountsOfCell = [NSMutableArray array];
	}
	return _maxElementCountsOfCell;
}

- (NSMutableArray *)combinationCellRanges
{
	if (!_combinationCellRanges) {
		_combinationCellRanges = [NSMutableArray array];
	}
	return _combinationCellRanges;
}

#pragma mark - setter
- (void)setCombinations:(NSArray *)combinations
{
    _combinations = combinations;
    [self setNeedsLayout];
}

#pragma mark - broadcast delegate
- (NSUInteger)cellCountOfBroadcastView:(MLBroadcastView *)broadcastView
{
    return self.broadcastCellCount;
}

- (MLBroadcastViewCell *)broadcastView:(MLBroadcastView *)broadcastView cellAtPageIndex:(NSUInteger)pageIndex
{
    static NSString *CellIdentifier = @"MLElementButtonBroadcastCell";
    MLElementButtonBroadcastCell *cell = [broadcastView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[MLElementButtonBroadcastCell alloc]initWithReuseIdentifier:CellIdentifier];
    }
    
    //找到其是哪个combination
    __block NSInteger cbIndex = -1;
    [self.combinationCellRanges enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSRange range = [obj rangeValue];
        if (NSLocationInRange(pageIndex,range)) {
            cbIndex = idx;
            *stop = YES;
        }
    }];
    NSAssert(cbIndex>=0, @"找不到对应的集合");
    
    MLElementButtonItemCombination *cb = self.combinations[cbIndex];
    
    NSRange range = [self.combinationCellRanges[cbIndex] rangeValue];
    
    //传递元素进去
    NSUInteger len = [self.maxElementCountsOfCell[cbIndex] integerValue];
    NSInteger cbPageIndex = pageIndex-range.location;
    if (cb.elements.count-cbPageIndex*len<len) {
        len = cb.elements.count-cbPageIndex*len;
    }
    NSArray *itemsOfCell = [cb.elements subarrayWithRange:NSMakeRange(cbPageIndex*[self.maxElementCountsOfCell[cbIndex] integerValue], len)];
    cell.items = itemsOfCell;
    
    return cell;
}

//滚到了某一个页面
- (void)didScrollToPageIndex:(NSUInteger)pageIndex ofBroadcastView:(MLBroadcastView *)broadcastView
{
    if (self.didScrollToPageIndexBlock) {
        //找到其是哪个combination
        __block NSInteger cbIndex = -1;
        [self.combinationCellRanges enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSRange range = [obj rangeValue];
            if (NSLocationInRange(pageIndex,range)) {
                cbIndex = idx;
                *stop = YES;
            }
        }];
        NSAssert(cbIndex>=0, @"找不到对应的集合2");
        
        NSRange range = [self.combinationCellRanges[cbIndex] rangeValue];
        self.didScrollToPageIndexBlock(cbIndex,range.length,pageIndex-range.location);
    }
}


#pragma mark - layout

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.bcView.frame = self.bounds;
    
    //计算出每个cell能放的玩意的数量
    [self.maxElementCountsOfCell removeAllObjects];
    [self.combinationCellRanges removeAllObjects];
    self.broadcastCellCount = 0;
    for (NSInteger i=0; i<self.combinations.count; i++) {
        MLElementButtonItemCombination *combination = self.combinations[i];
        if (combination.elements.count<=0) {
            continue;
        }
        
        CGFloat elementOccupyWidth = combination.elementWidth+combination.elementXSpacing*2;
        CGFloat elementOccupyHeight = combination.elementHeight+combination.elementYSpacing*2;
        //计算出这个集合的cell放的玩意的数量
        
        //计算出每行最多可以放几个
        NSInteger maxElementCountOfRow = MAX(1, floor((self.frameWidth-combination.elementXSpacing*2)/elementOccupyWidth));
        //计算出这个高度可以放置多少行
        NSInteger maxRowCountOfCell = MAX(1, floor((self.frameHeight-combination.elementYSpacing*2)/elementOccupyHeight));
        //计算出这个集合需要多少行
        NSInteger needTotalRowCount = ceil(combination.elements.count/(double)maxElementCountOfRow);
        
        //这个集合需要的cell数目
        NSInteger cellCountOfCB = ceil((double)needTotalRowCount/maxRowCountOfCell);
        NSInteger maxElementCountOfCell = maxElementCountOfRow*maxRowCountOfCell;
        
        NSRange range = NSMakeRange(self.broadcastCellCount, cellCountOfCB);
        [self.combinationCellRanges addObject:[NSValue valueWithRange:range]];
        self.broadcastCellCount += cellCountOfCB;
        [self.maxElementCountsOfCell addObject:@(maxElementCountOfCell)];
    
    }
    
    [self.bcView reloadData];
    
}

#pragma mark - outcall
- (void)scrollToCombinationIndex:(NSInteger)combinationIndex andCombinationPageIndex:(NSInteger)combinationPageIndex animated:(BOOL)animated
{
    if (combinationIndex<0||combinationIndex>=self.combinations.count) {
        return;
    }
    //找到真实是第几页
    NSRange range = [self.combinationCellRanges[combinationIndex] rangeValue];
    if (combinationPageIndex<0||combinationPageIndex>=range.length) {
        return;
    }
    NSInteger pageIndex = range.location+combinationPageIndex;
    
    [self.bcView scrollToPageIndex:pageIndex animated:animated];
}

@end
